package com.hupu.jrs.components.retrofit

import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
import android.telephony.TelephonyManager
import com.hupu.jrs.components.storage.UserStorage
import com.hupu.jrs.util.SecurityUtil
import com.hupu.jrs.util.SettingPrefUtil
import java.net.URLEncoder
import java.security.KeyStore
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
import java.util.HashMap

/**
 * Created by gzsll on 2014/9/23 0023.
 */
class RequestHelper(private val mContext: Context, private val mUserStorage: UserStorage) {

    val httpRequestMap: Map<String, String>
        get() {
            val map = HashMap<String, String>()
            map.put("client", deviceId)
            map.put("night", if (SettingPrefUtil.getNightModel(mContext)) "1" else "0")
            if (mUserStorage.isLogin) {
                try {
                    map.put("token", URLEncoder.encode(mUserStorage.token, "UTF-8"))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return map
        }

    val androidId: String
        get() = Settings.Secure.getString(mContext.contentResolver, Settings.Secure.ANDROID_ID)

    val deviceId: String
        @SuppressLint("MissingPermission")
        get() {
            val deviceId: String
            val tm = mContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            if (tm.deviceId == null) {
                deviceId = androidId
            } else {
                deviceId = tm.deviceId
            }
            return deviceId
        }

    fun getRequestSign(map: Map<String, String>): String {
        val list = MutableList<java.util.Map.Entry<String, String>>(map.entries.size)
        Collections.sort<java.util.Map.Entry<String, String>>(list) { lhs, rhs -> lhs.key.compareTo(rhs.key) }
        val builder = StringBuilder()
        var i = 0
        while (i < list.size) {
            if (builder.length > 0) {
                builder.append("&")
            }
            val map1 = list[i]
            builder.append(map1.key).append("=").append(map1.value)
            i = i + 1
        }
        builder.append(SettingPrefUtil.getHuPuSign(mContext))
        return SecurityUtil.getMD5(builder.toString())
    }
}
